package com.cbgolf.oa.activity.parkdetails;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.widget.ImageView;
import butterknife.ButterKnife;
import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.OnMarkerClickListener;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MultiPointItem;
import com.amap.api.maps.model.MultiPointOverlay;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Polygon;
import com.cbgolf.oa.R;
import com.cbgolf.oa.base.BaseActivity;
import com.cbgolf.oa.contract.IParkMapContract.IParkMapPresenter;
import com.cbgolf.oa.contract.IParkMapContract.IParkMapView;
import com.cbgolf.oa.contract.IParkMapContract.IParkMapWaiter;
import com.cbgolf.oa.entity.LatLon;
import com.cbgolf.oa.entity.ParkBean;
import com.cbgolf.oa.entity.ParkFair;
import com.cbgolf.oa.entity.ParkWayInfo;
import com.cbgolf.oa.entity.StatisticsInfo;
import com.cbgolf.oa.entity.StatisticsInfo.Customer;
import com.cbgolf.oa.event.EventPark;
import com.cbgolf.oa.event.Events;
import com.cbgolf.oa.manager.DataManager;
import com.cbgolf.oa.manager.DialogManager;
import com.cbgolf.oa.manager.DialogManager.IDialogManagerWaiter;
import com.cbgolf.oa.manager.LocationManager.ILocationWaiter;
import com.cbgolf.oa.manager.PopManager;
import com.cbgolf.oa.manager.WsStompManager;
import com.cbgolf.oa.manager.WsStompManager.IWsManagerWaiter;
import com.cbgolf.oa.presenter.ParkMapPresenterImp;
import com.cbgolf.oa.service.LocationService;
import com.cbgolf.oa.util.ClassUtil;
import com.cbgolf.oa.util.DataUtil;
import com.cbgolf.oa.util.DensityUtil;
import com.cbgolf.oa.util.MapUtil;
import com.cbgolf.oa.util.PermissionUtils;
import com.cbgolf.oa.util.ScreenUtil;
import com.cbgolf.oa.util.ServiceUtil;
import com.cbgolf.oa.util.TypeUtil;
import com.cbgolf.oa.util.Util;
import com.cbgolf.oa.util.ViewUtils;
import com.cbgolf.oa.views.ErrorView;
import com.cbgolf.oa.views.ParkMapViewImp;
import com.cbgolf.oa.widget.autolayout.AutoFrameLayout.LayoutParams;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor.AbortPolicy;
import java.util.concurrent.TimeUnit;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * 球场道路实况，地图巡场，球僮位置以及相关统计等
 *
 * @author lq
 * @date 2018/4/27
 */

public class ParkMapActivity extends BaseActivity implements IParkMapWaiter, LocationSource,
    IWsManagerWaiter {

  /**
   * presenter
   */
  private IParkMapPresenter presenter;
  /**
   * view
   */
  private IParkMapView view;
  /**
   * map
   */
  private MapView mMapView = null;
  private ImageView locationIv;
  private AMap aMap;
  /**
   * 球场范围经纬度，四点（左上，左下，右上，右下）
   */
  private List<LatLng> listParkRange = new ArrayList<>();
  /**
   * 球道经纬度，信息数据等会以此对象传进来
   */
  private ParkBean mData;
  /**
   * 球道
   */
  List<Polygon> listPolygon = new ArrayList<>();
  /**
   * 球僮maker
   */
  List<MultiPointOverlay> listCaddiePoint = new ArrayList<>();

  /**
   * 打球人maker
   */
  List<MultiPointOverlay> listPlayerPoint = new ArrayList<>();
  /**
   * 工作人员maker
   */
  List<MultiPointOverlay> listWorkerPoint = new ArrayList<>();

  /**
   * 经纬度转换完的李斯
   */
  private List<ParkWayInfo> listCovertedAll = new ArrayList<>();
  /**
   * 所有球道经纬度
   */
  private List<ParkFair> listFairAll = new ArrayList<>();
  /**
   * 所有球僮信息
   */
  private List<LatLon> listCaddie;

  private ErrorView errorView;
  /**
   * 是否发送成功
   */
  private boolean isSendSuccess;
  /**
   * 消息
   */
  private String message;
  /**
   * 收到消息时间
   */
  private long time;
  /**
   * 间隔时间
   */
  private final long DIS_TIME = 2000;


  @Override
  public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.a_park_map);
    mMapView = ButterKnife.findById(this, R.id.mapvi_parkmap);
    mMapView.onCreate(savedInstanceState);
    locationIv = ButterKnife.findById(this, R.id.iv_location);
    locationIv.setAlpha(0.7f);
    EventBus.getDefault().register(this);
    initDatas();
  }


  /**
   * 转换左上角经纬度
   */

  private LatLng getLeftLatLng() {
    if (null == mData || null == mData.courseFairwayInfo
        || null == mData.courseFairwayInfo.leftUpPoints) {
      return new LatLng(0, 0);
    }
    return new LatLng(TypeUtil.parseDauble(mData.courseFairwayInfo.leftUpPoints.lat),
        TypeUtil.parseDauble(mData.courseFairwayInfo.leftUpPoints.lng));
  }

  /**
   * 转换右上角经纬度
   */
  private LatLng getRightLatLng() {
    if (null == mData || null == mData.courseFairwayInfo
        || null == mData.courseFairwayInfo.rightDownPoints) {
      return new LatLng(0, 0);
    }
    return new LatLng(TypeUtil.parseDauble(mData.courseFairwayInfo.rightDownPoints.lat),
        TypeUtil.parseDauble(mData.courseFairwayInfo.rightDownPoints.lng));
  }

  /**
   * 查看打球人在场统计数据
   */
  @Override
  public void showPlayerPlaying() {
    Bundle b = new Bundle();
    b.putSerializable(DataManager.KEY_DATA, (Serializable) listCaddie);
    b.putSerializable(DataManager.KEY_ALL, (Serializable) listFairAll);
    ClassUtil.startActivity(this,
        new Intent(this, PlayerCaddieCarDetailsActivity.class)
            .putExtra(DataManager.KEY_TYPE, DataManager.STATISTICS_PLAYER_IN_PARK)
            .putExtras(b));
  }

  /**
   * 查看打球人未登记统计数据
   */
  @Override
  public void showPlayerOfNoReg() {
    ClassUtil.startActivity(this,
        new Intent(this, PlayerCaddieCarDetailsActivity.class)
            .putExtra(DataManager.KEY_TYPE, DataManager.STATISTICS_PLAYER_REG_DETAILS));
  }

  /**
   * 查看球车在用统计数据
   */
  @Override
  public void showCarOfUsing() {
    ClassUtil.startActivity(this,
        new Intent(this, PlayerCaddieCarDetailsActivity.class)
            .putExtra(DataManager.KEY_TYPE, DataManager.STATISTICS_CAR_USING));
  }

  /**
   * 查看球僮在场统计数据
   */
  @Override
  public void showCaddieOfWorking() {
    ClassUtil.startActivity(this,
        new Intent(this, PlayerCaddieCarDetailsActivity.class)
            .putExtra(DataManager.KEY_TYPE, DataManager.STATISTICS_CADDIE_IN_PARK));
  }


  /**
   * 收到推送 更新球僮位置
   */
  @Override
  public void onMessage(String msg) {
    if (0 != time && System.currentTimeMillis() - time < DIS_TIME) {
      return;
    }
    time = System.currentTimeMillis();
    message = msg;
    presenter.filterId(DataUtil.getList(message, LatLon.class));
  }

  @Override
  public void onSendOver(boolean isSuccess) {
    isSendSuccess = isSuccess;
  }

  /**
   * map settings
   * location button
   * zoom button
   * styles
   * postions
   * enable
   */
  private void setMapSetting() {
    if (aMap == null) {
      aMap = mMapView.getMap();
    }
    // 设置卫星地图模式，aMap是地图控制器对象。
    aMap.setMapType(AMap.MAP_TYPE_SATELLITE);
    //初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
    MyLocationStyle myLocationStyle = new MyLocationStyle();
//    myLocationStyle.myLocationIcon(BitmapDescriptorFactory
//        .fromResource(R.drawable.transdrawable));// 设置小蓝点的图标
    myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色
//    myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
    myLocationStyle.strokeWidth(0f);// 设置圆形的边框粗细
    aMap.setMyLocationStyle(myLocationStyle);
    aMap.setMyLocationRotateAngle(180);
    myLocationStyle.interval(LocationService.LOCATION_TIME);
    //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
    myLocationStyle.showMyLocation(true);
    aMap.setOnMarkerClickListener(new OnMarkerClickListener() {
      @Override
      public boolean onMarkerClick(Marker marker) {

        return false;
      }
    });
    myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);
    myLocationStyle.anchor(0.5f, 0.5f);
    //设置定位蓝点的Style
    aMap.setMyLocationStyle(myLocationStyle);
    // 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
    aMap.setMyLocationEnabled(true);
//    aMap.setLocationSource(this);
    //    UiSettings settings = aMap.getUiSettings();
//    settings.setMyLocationButtonEnabled(true);
//    //通过aMap对象设置定位数据源的监听
//    // 可触发定位并显示当前位置
//    aMap.setMyLocationEnabled(true);
//    settings.setZoomControlsEnabled(true);
//    settings.setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_RIGHT);

  }


  /**
   * map listener
   * marker onclick
   */
  private void setMapListener() {
    // 定义海量点点击事件
    AMap.OnMultiPointClickListener multiPointClickListener = new AMap.OnMultiPointClickListener() {
      // 海量点中某一点被点击时回调的接口
      // 返回 true 则表示接口已响应事件，否则返回false
      @Override
      public boolean onPointClick(MultiPointItem pointItem) {
        int type = TypeUtil.getInt(pointItem.getCustomerId());
        if (type == DataManager.CADDIE) {
          if (null != pointItem.getObject() && pointItem.getObject() instanceof LatLon) {
            LatLon l = (LatLon) pointItem.getObject();
            presenter.requestUserInfo(l.userId, type);
          }
        } else if (type == DataManager.WORKER) {
          showWorkerPop(pointItem, type);
        }
        return false;
      }
    };
    // 绑定海量点点击事件
    aMap.setOnMultiPointClickListener(multiPointClickListener);
  }

  private void initDatas() {
    view = new ParkMapViewImp(this, this, mMapView);
    errorView = new ErrorView(this);
    presenter = new ParkMapPresenterImp(view);
    presenter.getStatisticsInfo();
    setMapSetting();
    setMapListener();
    WsStompManager.getInstance().setWorker(this);
    if (null != mData) {
      setInitData();
    } else {
      presenter.getFirWayLatlon();
    }
    ViewUtils.setClick(locationIv, v ->
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(
            new LatLng(LocationService.getLat(), LocationService.getLon()))));
  }

  /**
   * 获取球场范围经纬度
   * 转换球道经纬度为map经纬度等
   */
  private void getPublicData() {
    ThreadFactory factory = r -> new Thread(r);
    ExecutorService service = new ThreadPoolExecutor(1, 1, 0L,
        TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1024), factory, new AbortPolicy());
    service.execute(() -> {
      listParkRange = MapUtil.getListLatlngRange(getLeftLatLng(), getRightLatLng());
      listCovertedAll = MapUtil.getCovertListWayInfo(mData);
    });
    service.shutdown();
  }

  @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
  public void getData(Events events) {
    if (null != events && events.msgTarget == DataManager.MAIN_PARK_DATA) {
      mData = events.parkBean;
      EventBus.getDefault().removeStickyEvent(Events.class);
    }
  }

  @Subscribe(threadMode = ThreadMode.MAIN)
  public void requestOver(EventPark event) {
    if (null == event) {
      return;
    }
    switch (event.msgTarget) {
      case DataManager.PARK_MAP_LATLON:
        mData = event.parkBean;
        if (null == mData) {
          event.errorMsg = "很抱歉，没有查询到球道数据";
          showError(event);
          return;
        }
        showMap();
        setInitData();
        break;
      case DataManager.PARK_MAP_STATISTICS:
        if (null != view) {
          view.requestOver(event);
        }
        break;
      case DataManager.PARK_MAP_FILTER_BUSSINESS:
        drawBusinessWay(event);

        break;
      case DataManager.PARK_MAP_UPDATE_CADDIE_PLAYER_WORKER_LOCATION:
        upDataCaddiePlayerWorkerLocation(event.parkBean);
        break;
      case DataManager.STATISTICS_PLAYER_PARKWAY_RATIO:
        if (null != view) {
          view.showParkWayRatio(event);
        }
        break;
      case DataManager.PARK_MAP_USER_INFO:
        view.stopProgress();
        showPopInfo(event.parkBean, event.mType);
        break;
      default:
        break;
    }
  }

  /**
   * draw business way
   */
  private void drawBusinessWay(EventPark event) {
    List<ParkWayInfo> list = event.listBusinessWays;
    List<Polygon> listP = new ArrayList<>();
    if (!Util.listIsNull(list)) {
      for (int i = 0; i < list.size(); i++) {
        listP.add(MapUtil.drawPolygon(aMap, list.get(i).fairwayPoints));
      }
    }
    if (!Util.listIsNull(listPolygon)) {
      for (int i = 0; i < listPolygon.size(); i++) {
        if (null != listPolygon.get(i)) {
          listPolygon.get(i).remove();
        }
      }
    }
    listPolygon.clear();
    if (!Util.listIsNull(listP)) {
      listPolygon.addAll(listP);
    }


  }

  /**
   * 初始数据
   */
  private void setInitData() {
    getPublicData();
    if (null != mData && null != mData.courseFairwayInfo) {
      listFairAll = mData.courseFairwayInfo.fairwayInfo;
    }
    MapUtil.moveToAreaCenter(aMap, getLeftLatLng(), getRightLatLng());
    MapUtil.drawTextMaker(aMap, mData);
    WsStompManager.getInstance().setParkBean(mData);
  }

  /**
   * 展示地图
   */
  private void showMap() {
    if (null != errorView) {
      errorView.showData(mMapView);
    }
    ViewUtils.setVisible(locationIv, true);
  }

  /**
   * 展示异常
   */
  private void showError(EventPark event) {
    if (null != errorView) {
      errorView.showError(mMapView, event.errorMsg, event.errorCode, null);
    }
    ViewUtils.setVisible(locationIv, false);
  }

  /**
   * initlocation
   */
  private void initLocation() {

    if (!PermissionUtils.hasAllMapPermission()) {
      DialogManager.getInstance().showRequestPermissionDialog(this,
          PermissionUtils.getLocationPermissionNames(),
          new IDialogManagerWaiter() {
            @Override
            public void doSubmit() {
              requestPermission(PermissionUtils.getLocationNeedPermission());
            }

            @Override
            public void doCancel() {
              finish();
            }
          });
    } else {
      checkWriteSetting();
      if (!ServiceUtil.isServiceRunning(context, LocationService.class.getName())) {
        startService(new Intent(this, LocationService.class));
      }
      if (!ServiceUtil.isOPen(context)) {
        ServiceUtil.openGPS(context);
      }
      if (LocationService.isStoped()) {
        LocationService.startLocation();
      }
      LocationService.setWorker(new ILocationWaiter() {
        @Override
        public void locationSuccess(AMapLocation location) {
          if (!isSendSuccess ||
              LocationService.isOutDis(LocationService.lastLatlng, LocationService.newLatlng)) {
            WsStompManager.getInstance().sendLatLngStomp();
          }
        }

        @Override
        public void locationFail() {
          LocationService.startLocation();
        }
      });
    }

  }

  /**
   * 点击地图上的点，展示详细
   */
  private void showPopInfo(ParkBean bean, int type) {
    if (null == bean) {
      return;
    }
    List<Customer> listCustomer = new ArrayList<>();
    StatisticsInfo.Customer customer;
    if (!Util.listIsNull(bean.customerInfo)) {
      for (int i = 0; i < bean.customerInfo.size(); i++) {
        customer = new StatisticsInfo().getCustomer();
        customer.name = bean.customerInfo.get(i).name;
        customer.customerId = bean.customerInfo.get(i).customerId;
        customer.customerCardId = bean.customerInfo.get(i).customerCardId;
        customer.customerCardNumber = bean.customerInfo.get(i).customerCardNumber;
        customer.hole = bean.customerInfo.get(i).hole;
        customer.courseCar = bean.customerInfo.get(i).courseCar;
        listCustomer.add(customer);
      }
    }
    StatisticsInfo info = new StatisticsInfo.Builder()
        .setUserId(bean.userId)
        .setUserName(bean.userName)
        .setLevelName(bean.levelName)
        .setPhone(bean.phone)
        .setIdentityType(bean.identityType)
        .setListCustomers(listCustomer)
        .build();
    PopManager.getInstance()
        .setWidth(ScreenUtil.getWidth() - DensityUtil.dip2px(context, 20))
        .setHeight(LayoutParams.WRAP_CONTENT)
        .setType(type)
        .setParkBean(new ParkBean.Builder()
            .setStatisticsInfo(info)
            .build())
        .showParkMapCaddiePlayerWorker(context);
  }

  private void showWorkerPop(MultiPointItem pointItem, int type) {
    StatisticsInfo info = null;
    if (null != pointItem.getObject() && pointItem.getObject() instanceof LatLon) {
      LatLon l = (LatLon) pointItem.getObject();
      List<Customer> listCustomer = new ArrayList<>();
      StatisticsInfo.Customer customer;
      if (!Util.listIsNull(l.customerNames)) {
        for (int i = 0; i < l.customerNames.size(); i++) {
          customer = new StatisticsInfo().getCustomer();
          customer.name = l.customerNames.get(i);
          listCustomer.add(customer);
        }
      }
      info = new StatisticsInfo.Builder()
          .setUserId(l.userId)
          .setCourseId(l.courseId)
          .setUserName(l.userName)
          .setLevelName(l.levelName)
          .setPhone(l.phone)
          .setHeadPic(l.headPic)
          .setCustomerCount(l.customerCount)
          .setIdentityType(l.identityType)
          .setDepartmentName(l.departmentName)
          .setListCustomers(listCustomer)
          .setLat(l.lat)
          .setLng(l.lng)
          .build();
    }
    PopManager.getInstance()
        .setWidth(ScreenUtil.getWidth() - DensityUtil.dip2px(context, 20))
        .setHeight(LayoutParams.WRAP_CONTENT)
        .setType(type)
        .setParkBean(new ParkBean.Builder()
            .setStatisticsInfo(info)
            .build())
        .showParkMapCaddiePlayerWorker(context);
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    mMapView.onDestroy();
    EventBus.getDefault().unregister(this);
  }

  @Override
  protected void onResume() {
    super.onResume();
    mMapView.onResume();
    initWsStomp();
    initLocation();
  }

  private void checkWriteSetting() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
      if (!Settings.System.canWrite(this)) {
        DialogManager.getInstance().showSettingDialog(this, false,
            new IDialogManagerWaiter() {
              @Override
              public void doSubmit() {
                try {
                  Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS,
                      Uri.parse("package:" + getPackageName()));
                  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                  startActivityForResult(intent, REQUEST_CODE_ASK_WRITE_SETTINGS);
                } catch (Exception e) {
                }
              }

              @Override
              public void doCancel() {
              }
            });
        return;
      }
    }
    DialogManager.getInstance().release();
  }

  private void initWsStomp() {
      WsStompManager.getInstance().sendLatLngStomp();
  }

  @Override
  protected void onPause() {
    super.onPause();
    mMapView.onPause();
  }

  @Override
  protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    mMapView.onSaveInstanceState(outState);
  }

  @Override
  public String getActivityTitle() {
    return "球场管理";
  }

  @Override
  public void back() {
    finish();
  }

  @Override
  public void refresh() {
    presenter.getStatisticsInfo();
  }


  @Override
  public void upDataCaddiePlayerWorkerLocation(ParkBean bean) {
    if (null == bean) {
      Util.show("sorry updata error");
      return;
    }
    if (null != view) {
      view.showPlayerNumInPark(bean.inParkPlayerNum);
    }
    upDataPoints(bean);


  }

  /**
   * 更新地图上的那些点
   */
  private void upDataPoints(ParkBean bean) {
    ThreadFactory factory = r -> new Thread(r);
    ExecutorService service = new ThreadPoolExecutor(1, 1, 0L,
        TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1024), factory);
    service.execute(() -> {
      listCaddie = bean.listCaddie;
      List<MultiPointOverlay> listCaddieP = new ArrayList<>();
      List<MultiPointOverlay> listPlayerP = new ArrayList<>();
      List<MultiPointOverlay> listWorkerP = new ArrayList<>();
      if (!Util.listIsNull(bean.listCaddieLatLng)) {
        for (int i = 0; i < bean.listCaddieLatLng.size(); i++) {
          listCaddieP.add(MapUtil.drawMakers(aMap, DataManager.CADDIE, bean, listParkRange));
        }
      }
      if (!Util.listIsNull(bean.listPlayerLatLng)) {
        for (int i = 0; i < bean.listPlayerLatLng.size(); i++) {
          listPlayerP
              .add(MapUtil.drawMakers(aMap, DataManager.PLAYER, bean, listParkRange));
        }
      }
      if (!Util.listIsNull(bean.listWorderLatlng)) {
        for (int i = 0; i < bean.listWorderLatlng.size(); i++) {
          listWorkerP
              .add(MapUtil.drawMakers(aMap, DataManager.WORKER, bean, listParkRange));
        }
      }
      MapUtil.removePoints(listCaddiePoint);
      MapUtil.removePoints(listPlayerPoint);
      MapUtil.removePoints(listWorkerPoint);
      listCaddiePoint.clear();
      listPlayerPoint.clear();
      listWorkerPoint.clear();
      listCaddiePoint.addAll(listCaddieP);
      listPlayerPoint.addAll(listPlayerP);
      listWorkerPoint.addAll(listWorkerP);
      bean.ListParkWayInfoCoverted = listCovertedAll;
      presenter.filterCaddieNum(bean);
      presenter.filterCaddieWorking(bean);
    });
    service.shutdown();

  }

  @Override
  public void activate(OnLocationChangedListener onLocationChangedListener) {
//    if (!isOutRange) {
//      MapUtil.moveToAreaNoZoom(aMap, getLeftLatLng(), getRightLatLng());
//    } else {
//      aMap.moveCamera(
//          CameraUpdateFactory.changeLatLng(
//              new LatLng(LocationService.getLat(), LocationService.getLon())));
//    }
  }

  @Override
  public void deactivate() {

  }


  @Override
  public void onOutRange() {
    MapUtil.removePoints(listCaddiePoint);
    MapUtil.removePoints(listPlayerPoint);
    MapUtil.removePoints(listWorkerPoint);
  }


  private final int REQUEST_CODE_ASK_WRITE_SETTINGS = 12345;

  @Override
  protected void getPermissionSuccess() {
    if (!ServiceUtil.isServiceRunning(context, LocationService.class.getName())) {
      startService(new Intent(this, LocationService.class));
    }
    if (!ServiceUtil.isOPen(context)) {
      ServiceUtil.openGPS(context);
    }
    LocationService.startLocation();
    checkWriteSetting();

  }

  @Override
  protected void getPermissionFail() {
    finish();
  }


}
